<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Mews\Captcha\Facades\Captcha;

class LoginController extends Controller
{
    use ResetsPasswords;

    public function showLoginForm(){
        return view('admin.auth.login');
    }

    public function login(Requests\LoginRequest $request){
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password, 'status' => 1], $request->remember)){
            add_admin_log('用户登录', $request);
            return redirect('/admin');
        }else{
            return redirect()->back()->withErrors('用户名或密码错误');
        }
    }

    public function logout(){
        Auth::guard('admin')->logout();
        return redirect('/admin/login');
    }

    public function showResetForm(){
        return view('admin.auth.reset');
    }

    public function resetPassword(Requests\PasswordRequest $requests){
        $data = $requests->all();
        $user = Auth::guard('admin')->user();
        if (\Hash::check($data['oldpassword'], $user->password)){
            $user->password = bcrypt($data['password']);
            if ($user->save()){
                exit(json_encode(array('code'=>1, 'url'=>'/admin/home')));
            }else{
                exit(json_encode(array('code'=>0, 'msg'=>'参数错误!')));
            }
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>'原密码不正确')));
        }
    }

    public function verifyImg(){
        return Captcha::src();
    }
}
